const Promise = require('./es6-promise-min');
const Const = require('./const');
const Data = require('./data');

let apiList = {
    Wx: {
        encryptedData: ['wx/encrypted-data', 'code', 'encrypted_data', 'iv'],
        searchByName: ['wx/search-by-name', 'org_root_id', 'project_id', 'name'],
        createWxQrcode: ['wx/create-wx-qrcode', 'path', 'width']
    },
    Common: {
        sendCode: ['common/phone-verification-code-send', 'phone']
    },
    User: {
        login: ['user/login', 'phone', 'password'],
        register: ['user/register', 'phone', 'password', 'code'],
        resetPassword: ['user/password-reset', 'phone', 'password', 'code'],
        getUserByWx: ['user/get-user-by-wx', 'unionid']
    }
};

let api = {};

for (let moduleKey in apiList) {
    let moduleApiList = apiList[moduleKey];
    api[moduleKey] = {};
    for (let functionName in moduleApiList) {
        let config = moduleApiList[functionName];
        api[moduleKey][functionName] = (function (config) {
            return function () {
                let action = config[0];
                let data = {};
                if (config.length > 1) {
                    for (let i = 1; i < config.length; i++) {
                        let key = config[i];
                        let value = arguments[i - 1];
                        if (value === undefined) {
                            continue;
                        }
                        data[key] = value;
                    }
                }
                return post(action, data);
            };
        })(config);
    }
}

function transformObjectToUrlencodedData(obj) {
    let p = [];
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            p.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
        }
    }
    return p.join('&');
}

function post(url, params) {
    let token = Data.getToken() || "";
    let host = Const.NET.END_POINT;
    return new Promise((resolve, reject) => {
        let requestData = Object.assign({
            token: token,
            client: Const.NET.CLIENT,
            version: Const.NET.VERSION
        }, params);

        wx.request({
            url: `${host}/${url}`,
            data: requestData,
            method: "POST",
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            success: function (res) {
                if (res.data.code == 0) {
                    resolve(res.data.data);
                }

                if (res.data.hasOwnProperty('code')) {
                    reject({
                        code: res.data.code,
                        message: res.data.message
                    })
                }

                reject({
                    code: Const.ERROR.ERROR_NETWORK,
                    response: res
                });
            },
            fail: function (reason) {
                reject({
                    code: Const.ERROR.ERROR_NETWORK,
                    response: reason
                })
            }
        });
    });
}

module.exports = api;
